/*
 * FileName：LoginCtrl.java 
 * <p>
 * Copyright (c) 2017-2020, <a href="http://www.webcsn.com">hermit (1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package com.smart.primary.sys.ctrl;


import com.alipay.api.domain.Account;
import com.smart.primary.common.common.BaseCtrl;
import com.smart.primary.common.common.Constants;
import com.smart.primary.common.util.*;
import com.smart.primary.sys.service.ResService;
import com.smart.primary.sys.service.UserService;
import com.smart.primary.sys.vo.Res;
import com.smart.primary.sys.vo.User;
import com.smart.primary.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 *
 * @author hermit
 * @version 2.0
 * @date 2018-04-17 10:54:58
 */
@Controller
@RequestMapping("user")
public class LoginCtrl extends BaseCtrl {
    
    @Autowired
    private UserService sysUserService;
    
    @Autowired
    private ResService sysResService;


    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public AjaxResult login(User user)
            throws Exception {
        user.setUserPwd(MD5Util.getMD5Code(user.getUserPwd()));
        User sysUser = this.sysUserService.queryObject(user);
        if (sysUser == null) {
            return AjaxResult.failure("用户名或者密码错误");
        }
        SessionUtil.setUser(request,response,sysUser);

        List<Res> objectList = sysResService.getMenuList(sysUser.getUserId());
        SessionUtil.setAttr(request,response,Constants.SESSION_MENU_LIST, objectList);
        return AjaxResult.success(sysUser.getUserNickname());
    }

    @ResponseBody
    @RequestMapping(value = "/updatepwd", method = RequestMethod.POST)
    public AjaxResult updatepwd(User user)
        throws Exception {
        User sessionuser=SessionUtil.getUser(request,response);
        if (!sessionuser.getUserPwd().equals(MD5Util.getMD5Code(user.getUserPwd()))) {
            return AjaxResult.failure("用户名或密码错误");
        }
        user.setUserPwd(MD5Util.getMD5Code(user.getUserNewPwd()));
        user.setUserId(sessionuser.getUserId());
        this.sysUserService.update(user);
        // 注销用户
        request.getSession().invalidate();
        return AjaxResult.success();
    }
    
    /**
     * 用户退出
     * 
     * @return
     */
    @ResponseBody
    @RequestMapping("logout")
    public AjaxResult logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return AjaxResult.success();
    }

    /**
     * 用户注册
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("register")
    public AjaxResult register(User user, String verificationCode, String userEmailCode) throws Exception {
        if (StringUtil.isBlank(user.getUserName()) || StringUtil.isBlank(user.getUserPwd()) || StringUtil.isBlank(verificationCode)|| StringUtil.isBlank(userEmailCode)) {
            return AjaxResult.failure("输入不完整");
        }
        if (!WebUtils.getSessionAttribute(request, Constants.SESSION_VERIFY_CODE).equals(StringUtil.upperCase(verificationCode))) {
            return AjaxResult.failure("图形验证码错误");
        }
        if (!WebUtils.getSessionAttribute(request, Constants.SESSION_MAIL_CODE).equals(StringUtil.upperCase(userEmailCode))) {
            return AjaxResult.failure("邮箱验证码错误");
        }
        //判断是否登录名重复
        Integer count = sysUserService.queryCount(user);
        if (count != null && count > 0) {
            return AjaxResult.failure("用户名重复");
        }
        sysUserService.insert(user);
        return AjaxResult.success();
    }

    /**
     * 用户注册-发送邮箱验证码
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("sendmail")
    public AjaxResult sendMail(User user, String verificationCode) throws Exception {
        if (StringUtil.isBlank(user.getUserName()) ||  StringUtil.isBlank(verificationCode)) {
            return AjaxResult.failure("保存失败");
        }
        if(!ValidateUtil.isEmail(user.getUserName())){
            return AjaxResult.failure("邮箱输入错误");
        }
        if (!WebUtils.getSessionAttribute(request, Constants.SESSION_VERIFY_CODE).equals(StringUtil.upperCase(verificationCode))) {
            return AjaxResult.failure("验证码错误");
        }
        //判断是否登录名重复
        Integer count = sysUserService.queryCount(user);
        if (count != null && count > 0) {
            return AjaxResult.failure("用户名重复");
        }
        //生成验证码
        String code = Util.bulidMobileCode(6);
        WebUtils.setSessionAttribute(request,Constants.SESSION_MAIL_CODE,code);
        MailUtil.sendMail(user.getUserName(), "smart-admin验证码", "尊敬的用户您好,您本次注册的验证码是: " + code);
        return AjaxResult.success();
    }
}
